import 'dart:convert';
import 'dart:developer';

import 'package:FlutterDemo/widget/practicalextension/flutterbloc/practicale/models/CommonEntry.dart';
import 'package:FlutterDemo/widget/practicalextension/flutterbloc/practicale/models/ItemModel.dart';
import 'package:dio/dio.dart';
import 'package:http/http.dart' show Client;

class MovieApiProvider {
  final String URL = 'http://api.themoviedb.org/3/movie/popular?api_key=';
  final String _apkKey = '802b2c4b88ea1183e50e6b285a27696e';
  Client client = Client();

  Dio get http => _dio;

  late Dio _dio;

  static const String BASE_URL = "http://api.themoviedb.org";
  static const String BASE_URL2 = "http://country.io";

  static const int CONNECT_TIMEOUT = 50000;
  static const int RECEIVE_TIMEOUT = 30000;

  /// http 请求
  Future<ItemModel> fetchMovieList() async {
    log("MovieApiProvider fetchMovieList");
    StringBuffer sb = StringBuffer();
    sb.write(URL);
    sb.write(_apkKey);
    var url = sb.toString();
    log("MovieApiProvider fetchMovieList url: $url");
    final response = await client.get(Uri.parse(url));
    log("MovieApiProvider fetchMovieList content: ${response.body.toString()}");
    if (response.statusCode == 200) {
      return ItemModel.fromJson(json.decode(response.body));
    } else {
      throw Exception("Failed to load post");
    }
  }

  /// dio 请求
  Future<ItemModel> fetchMovieList2() async {
    var options = BaseOptions(
        baseUrl: BASE_URL,
        connectTimeout: CONNECT_TIMEOUT,
        receiveTimeout: RECEIVE_TIMEOUT,
        responseType: ResponseType.plain);
    try {
      // _dio = Dio(options).interceptors.add(MyInterceptor());
      _dio = Dio(options);
      // _dio.interceptors.add(MyInterceptor());
    } catch (e) {
      print(e);
    }

    var response = await _dio.get("/3/movie/popular?api_key=$_apkKey");
    log("response: $response");
    var r = response.data;
    if (response.statusCode == 200) {
      return ItemModel.fromJson(json.decode(r));
    } else {
      throw Exception("Failed to load post");
    }
  }

  /// dio 请求
  Future<PhoneEntry> fetchMovieList3() async {
    var options = BaseOptions(
      baseUrl: BASE_URL2,
      connectTimeout: CONNECT_TIMEOUT,
      receiveTimeout: RECEIVE_TIMEOUT,
    );
    try {
      // _dio = Dio(options).interceptors.add(MyInterceptor());
      _dio = Dio(options);
      // _dio.interceptors.add(MyInterceptor());
    } catch (e) {
      print(e);
    }

    var response = await _dio.get("/phone.json");
    log("response: $response");
    Map<String, dynamic> r = response.data;
    if (response.statusCode == 200) {
      var list = <CommonEntry>[];
      r.entries.forEach((element) {
        list.add(CommonEntry(element.key, "${element.value}"));
      });
      log("response: list-len: ${list.length}");
      var phoneEntry = PhoneEntry(list);
      return phoneEntry;
    } else {
      throw Exception("Failed to load post");
    }
  }
}
